package com.xindaoapp.happypet.activity;

import java.text.DecimalFormat;
import java.util.LinkedList;
import java.util.List;

import android.content.Intent;
import android.graphics.Movie;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.api.AddClient;
import com.xindaoapp.happypet.api.Address;
import com.xindaoapp.happypet.bean.Good;
import com.xindaoapp.happypet.bean.SerachGood;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.view.pulltorefresh.PullToRefreshBase;
import com.xindaoapp.happypet.view.pulltorefresh.PullToRefreshBase.OnRefreshListener;
import com.xindaoapp.happypet.view.pulltorefresh.PullToRefreshListView;

public class NewGoodsActivity extends BaseLoadAnimationAcitivity implements OnClickListener {
    @ViewInject(R.id.new_goods_list)
    private PullToRefreshListView goods_list;
    @ViewInject(R.id.no_result)
    private RelativeLayout no_result;

    @ViewInject(R.id.tittle_shop_cancel)
    private ImageView tittle_shop_cancel;
    @ViewInject(R.id.tittle_shop_content)
    private TextView tittle_shop_content;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Movie.decodeFile("");
        setContentView(R.layout.activity_newgoods);
        super.onCreate(savedInstanceState);
        ViewUtils.inject(this);
        initClick();
        initList();
    }

    private void initClick() {
        tittle_shop_cancel.setOnClickListener(this);
        tittle_shop_content.setText("尾巴圈尝鲜");
    }

    private int page;

    private void initList() {
        page = 1;
        fillData(page);
        goods_list.setPullLoadEnabled(true);
        goods_list.setPullRefreshEnabled(true);
        goods_list.setOnRefreshListener(new OnRefreshListener<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                goods.clear();
                page = 1;
                fillData(page);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                fillData(++page);
            }
        });
        goods_list.getRefreshableView().setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(final AdapterView<?> parent, View view, final int position,
                    long id) {
                try {
                    goods.get(position).setSold_number(
                            Integer.parseInt(goods.get(position).getSold_number()) + 1 + "");
                    adapter.notifyDataSetChanged();
                    Intent intent = new Intent(NewGoodsActivity.this, ProductDetailActivity1.class);
                    intent.putExtra("productId",
                            ((Good) parent.getItemAtPosition(position)).getGoods_id());
                    startActivity(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private final LinkedList<Good> goods = new LinkedList<Good>();
    private GoodSerachAdapter adapter;
    private boolean isFirst = true;

    private void fillData(final int page) {
        RequestParams params = new RequestParams();
        params.put("page", String.valueOf(page));
        params.put("pageSize", Address.PAGECOMMONSIZE);
        // final ProgressHUD ProgressDialog = ProgressHUD.show(this, "正在加载...", true, true, null);
        AddClient.get(Address.GOODSNEW, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, String content) {
                try {
                    isFirst = false;
                    onDataArrived(true);
                    SerachGood parse = JSON.parseObject(content, SerachGood.class);
                    if (parse.getStatus().equals("1") && parse.getData() != null) {
                        if (Integer.parseInt(parse.getData().getCount()) > 0) {
                            List<Good> info = parse.getData().getInfo();
                            goods.addAll(info);
                            if (adapter == null) {
                                adapter = new GoodSerachAdapter(goods);
                                goods_list.getRefreshableView().setAdapter(adapter);
                            } else {
                                adapter.notifyDataSetChanged();
                            }
                        }
                    } else {
                        Toast.makeText(NewGoodsActivity.this, "没有更多数据", Toast.LENGTH_SHORT).show();
                    }
                    onLoaded();
                } catch (Exception e) {
                    e.printStackTrace();
                    no_result.setVisibility(View.VISIBLE);
                    goods_list.setVisibility(View.GONE);
                }
                super.onSuccess(statusCode, content);
            }

            @Override
            public void onFailure(Throwable error, String content) {
                onLoaded();
                if (isFirst) {
                    onDataArrived(false);
                    SetOnLoadFailListener(new OnLoadFailListener() {
                        @Override
                        public void onLoadFail() {
                            fillData(1);
                        }
                    });
                } else {
                    onDataArrived(true);
                }
                super.onFailure(error, content);
            }
        });
        setLastUpdateTime();
    }

    private void onLoaded() {
        goods_list.onPullDownRefreshComplete();
        goods_list.onPullUpRefreshComplete();
    }

    private void setLastUpdateTime() {
        String text = CommonUtil.formatPullToRefreshDate();
        goods_list.setLastUpdatedLabel(text);
    }

    private class GoodSerachAdapter extends BaseAdapter {
        private final List<Good> goods2;

        public GoodSerachAdapter(List<Good> goods2) {
            super();
            this.goods2 = goods2;
        }

        @Override
        public int getCount() {
            return goods2.size();
        }

        @Override
        public Object getItem(int position) {
            return goods2.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = View.inflate(NewGoodsActivity.this, R.layout.good_common_item, null);
                holder = new ViewHolder();
                holder.good_pic = (ImageView) convertView.findViewById(R.id.good_pic);
                holder.good_name = (TextView) convertView.findViewById(R.id.good_name);
                holder.good_shop_price = (TextView) convertView.findViewById(R.id.good_shop_price);
                holder.good_market_price =
                        (TextView) convertView.findViewById(R.id.good_market_price);
                holder.good_sell = (TextView) convertView.findViewById(R.id.good_sell);
                holder.good_surplus = (TextView) convertView.findViewById(R.id.good_surplus);
                holder.goods_comment = (TextView) convertView.findViewById(R.id.goods_comment);
                holder.good_dazhe = (TextView) convertView.findViewById(R.id.good_dazhe);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.good_name.setText(goods2.get(position).getGoods_name());
            holder.good_name.setText(goods2.get(position).getGoods_name());
            holder.good_shop_price.setText(formatPrice(Float.valueOf(goods2.get(position)
                    .getShop_price())));
            holder.good_market_price.setText("￥"
                    + formatPrice(Float.valueOf(goods2.get(position).getMarket_price())));
            holder.good_market_price.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
            holder.good_sell.setText(goods2.get(position).getSold_number());
            holder.good_surplus.setText(goods2.get(position).getGoods_number());
            holder.goods_comment.setText(goods2.get(position).getComment_percent());

            ImageLoader.getInstance().displayImage(goods2.get(position).getGoods_thumb(),
                    holder.good_pic);
            float a =
                    (Float.valueOf(goods2.get(position).getShop_price()) / Float.valueOf(goods2
                            .get(position).getMarket_price())) * 10;
            holder.good_dazhe.setText(formatDaZhe(a) + "折");
            return convertView;
        }
    }

    private String formatDaZhe(Float a) {
        DecimalFormat df = new DecimalFormat("0.0");
        return df.format(a);
    }

    private String formatPrice(Float a) {
        DecimalFormat df = new DecimalFormat("0.00");
        return df.format(a);
    }

    public class ViewHolder {
        ImageView good_pic;
        TextView good_name;
        TextView good_shop_price;
        TextView good_market_price;
        TextView good_sell;
        TextView good_surplus;
        TextView goods_comment;
        TextView good_dazhe;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tittle_shop_cancel:
                finish();
                break;
            default:
                break;
        }
    }
}
